let remainingQuestions = [...questions];
let masteredQuestions = [];
let testedCount = 0;
let errorCount = {};
questions.forEach(q => errorCount[q] = 0);

// 初始化进度显示
const masteredCountSpan = document.getElementById('mastered-count');
const totalCountSpan = document.getElementById('total-count');
const progressBar = document.getElementById('progress-bar');
totalCountSpan.textContent = questions.length;

// 获取模态框元素
const masteredModal = document.getElementById('mastered-modal');
const unmasteredModal = document.getElementById('unmastered-modal');
const unmasteredMessage = document.getElementById('unmastered-message');
const masteredClose = masteredModal.querySelector('.close');
const unmasteredClose = unmasteredModal.querySelector('.close');
const masteredConfirm = document.getElementById('mastered-confirm');
const unmasteredConfirm = document.getElementById('unmastered-confirm');

// 关闭模态框的函数
function closeModal(modal) {
    modal.style.display = 'none';
}

// 绑定关闭模态框事件
masteredClose.addEventListener('click', () => closeModal(masteredModal));
unmasteredClose.addEventListener('click', () => closeModal(unmasteredModal));

// 更新进度条
function updateProgressBar() {
    const mastered = masteredQuestions.length;
    const total = questions.length;
    const percentage = (mastered / total) * 100;
    progressBar.style.width = `${percentage}%`;
    const progressText = document.querySelector('.progress-text');
    progressText.textContent = `当前进度: ${mastered}/${total} 已掌握`;
}

// 显示下一题
function showNextQuestion() {
    const questionDiv = document.getElementById('question');
    if (remainingQuestions.length > 0) {
        // 随机选择一个题目
        const randomIndex = Math.floor(Math.random() * remainingQuestions.length);
        const currentQuestion = remainingQuestions.splice(randomIndex, 1)[0];
        testedCount++;
        masteredCountSpan.textContent = masteredQuestions.length;
        questionDiv.textContent = `问题 ${testedCount}: ${currentQuestion.slice(5)}`;
        updateProgressBar();
    } else {
        showTestResult();
    }
}

// 标记为掌握
function markAsMastered() {
    const questionDiv = document.getElementById('question');
    const currentQuestionText = questionDiv.textContent.slice(`问题 ${testedCount}: `.length);
    const fullQuestion = questions.find(q => q.slice(5) === currentQuestionText);
    masteredQuestions.push(fullQuestion);
    remainingQuestions = remainingQuestions.filter(q => q!== fullQuestion);
    masteredCountSpan.textContent = masteredQuestions.length;
    masteredModal.style.display = 'block';
    masteredConfirm.addEventListener('click', function () {
        closeModal(masteredModal);
        showNextQuestion();
        masteredConfirm.removeEventListener('click', arguments.callee);
    });
    updateProgressBar();
}

// 标记为未掌握
function markAsUnmastered() {
    const questionDiv = document.getElementById('question');
    const currentQuestionText = questionDiv.textContent.slice(`问题 ${testedCount}: `.length);
    const fullQuestion = questions.find(q => q.slice(5) === currentQuestionText);
    remainingQuestions.push(fullQuestion);
    errorCount[fullQuestion]++;
    unmasteredMessage.textContent = `✗ 题目已重新放回题库，当前题目为: ${fullQuestion.slice(0, 5)}，请注意复习`;
    unmasteredModal.style.display = 'block';
    unmasteredConfirm.addEventListener('click', function () {
        closeModal(unmasteredModal);
        showNextQuestion();
        unmasteredConfirm.removeEventListener('click', arguments.callee);
    });
}

// 显示测试结果
function showTestResult() {
    const resultDiv = document.getElementById('result');
    if (masteredQuestions.length === questions.length) {
        alert("🎉 恭喜！你已经掌握了所有题目！");
    } else {
        alert(`测试结束，共掌握了 ${masteredQuestions.length}/${questions.length} 道题`);
    }
    resultDiv.innerHTML = '<h2 class="text-xl font-bold mb-4">已掌握的题目</h2>';
    masteredQuestions.sort((a, b) => errorCount[b] - errorCount[a]);
    masteredQuestions.forEach((q, i) => {
        resultDiv.innerHTML += `<p class="mb-2">${i + 1}. ${q.slice(5)} (错误次数: ${errorCount[q]})</p>`;
    });
    resultDiv.style.display = 'block';
    updateProgressBar();
    // 禁用按钮
    const yesButton = document.getElementById('yes-button');
    const noButton = document.getElementById('no-button');
    yesButton.disabled = true;
    noButton.disabled = true;
}

// 绑定按钮事件
const yesButton = document.getElementById('yes-button');
const noButton = document.getElementById('no-button');
yesButton.addEventListener('click', markAsMastered);
noButton.addEventListener('click', markAsUnmastered);

// 开始显示第一题
showNextQuestion();